<?php

class Admin extends App {

	/**
	 * @var Modules
	 */
	private $_module;
	/**
	 * @var string
	 */
	private $_action;

	protected function __construct() {
		parent::__construct();
	}

	public static function getInstance($className = __CLASS__) {
		return parent::getInstance($className);
	}

	public function adminAccess() {
		$user = UserAccess::user();

		if ($user) return $user;


		if (!$user) {
			if (isset($_REQUEST['login']) && isset($_REQUEST['login']['login']) && isset($_REQUEST['login']['password'])) {
				$_REQUEST['login']['password'] = UserAccess::hash($_REQUEST['login']['password']);

				$user = UserAccess::loadInSession($_REQUEST['login']);

				if (!$user) {
					$this->tpl()->assign('error', "Неверный логин или пароль.");
					$user = false;
				} else if ($user->active != 1) {
					$this->tpl()->assign('error', "Ваша учетная запись заблокированная администрацией, либо вы еще не активировали её.");
					$user = false;
				} else if (!UserAccess::adminAccess()) {
					$this->tpl()->assign('error', "Доступ в административный раздел для вас ограничен.");
					$user = false;
				}
			}
		}

		return $user;

	}

	private function _login() {
		$login = isset($_REQUEST['login']) ? $_REQUEST['login'] : array('login' => "", "password" => "");
		$this->tpl()->assign('login', $login);
		$this->tpl()->display('login.html');
	}

	public function init() {
		parent::init();

		if (!$this->adminAccess()) {
			$this->_login();
			exit();
		}
	}

	public function run() {
		$this->init();

		$module = !empty($_REQUEST['module']) ? $_REQUEST['module'] : 'pages';
		$action = !empty($_REQUEST['action']) ? $_REQUEST['action'] : 'index';

		$module = Module::getModule($module);
		$this->_module = new $module($action, true);
		$content = $this->_module->render();

		if (self::$XMLHttpRequest) {
			echo $content;
			exit();
		}

		$this->tpl()->template_dir = RP . "tpl/admin/";
		$this->tpl()->assign(array(
			'_module' => $this->_module,
			'submenu' => $this->_module->subMenu(),
			'menu' => Modules::adminMenu(),
			'title' => $this->_module->title,
			'content' => $content,
		));
		
		$errors = Error::getErrors();
		if(count($errors)) $this->tpl()->assign ('errors', Error::render());
		
		$this->tpl()->display('index.html');
	}

	public function tpl() {
		if (!$this->_tpl) {
			$this->_tpl = new Templater(RP . "tpl/admin/");
		}

		return $this->_tpl;
	}

}